package com.itlong.cloud.controller.sdkV1.old.serverClient;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.itlong.cloud.POJO.DTO.property.PropertyProjectGetBuildInfoDTO;
import com.itlong.cloud.POJO.DTO.sdk.SDKRoomInfoSaveDTO;
import com.itlong.cloud.POJO.DTO.sdk.SDKUnitInfoSaveDTO;
import com.itlong.cloud.POJO.PO.*;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.PropertyPublicRoleEnum;
import com.itlong.cloud.enumerate.oldapp.Code;
import com.itlong.cloud.enumerate.oldapp.Message;
import com.itlong.cloud.project.sdk.ISDKServerOldBuildServiceClient;
import com.itlong.cloud.project.sdk.ISDKServerOldProjectServiceClient;
import com.itlong.cloud.project.sdk.ISDKServerOldRoomServiceClient;
import com.itlong.cloud.project.sdk.ISDKServerOldUnitServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.sdk.ISDKServerOldUserServiceClient;
import com.itlong.cloud.utils.encrypt.DesEncryptUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <desc>
 *      SDK服务端项目信息Controller
 * </desc>
 *
 * @createDate 2017/10/26
 */
@RestController
@RequestMapping("/jiabanjing/interface")
public class SDKServerOldProjectController {

    private static Logger LOG = LoggerFactory.getLogger(SDKServerOldProjectController.class);

    @Autowired
    ISDKServerOldUserServiceClient iSDKUserServiceClient;

    @Autowired
    ISDKServerOldProjectServiceClient iSDKProjectServiceClient;

    @Autowired
    ISDKServerOldBuildServiceClient iSDKBuildServiceClient;

    @Autowired
    ISDKServerOldUnitServiceClient iSDKServerOldUnitServiceClient;

    @Autowired
    ISDKServerOldRoomServiceClient iSDKRoomServiceClient;


   /**
    * <desc>
    *      SDK添加项目，申请项目
    * <desc/>
    * @param    appid     独立开发者的userId
    * @param    projectName     申请项目名称
    * @return   Message   老版标准格式化响应结果
    * @author Biao.R
    * @createDate 2017/11/6
    */
    @ResponseBody
    @RequestMapping("/app/project/add")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_ADD_PROJECT_LOG_DESC)
    public Message sdkAddProject(String appid, String projectName) {
        JSONObject js = new JSONObject();
        try {
            if (StringUtils.isEmpty(projectName)) {
                return new Message(Code.PARAM_ERR, "projectName不能为空");
            }
            Map<String, Object> params = new HashMap<>();
            params.put("projectName", projectName.trim());
            List<ProjectPO> projectInfos = iSDKProjectServiceClient.getByParamMap(params);
            if (null != projectInfos && projectInfos.size() > 0) {
                return new Message(Code.PARAM_ERR, "projectName已经存在，请不要重复添加");
            }
            ProjectPO projectPO = iSDKProjectServiceClient.saveByProjectName(appid, projectName);
            if (projectPO != null) {
                String projectId = projectPO.getProjectId();
                js.put("projectId", DesEncryptUtil.projectIdEncrypt(projectId, null, null));
                js.put("projectName", projectName.trim());
            }
            return new Message(Code.SUCCESS, js);
        } catch (Exception e) {
            throw new DataAccessException("【SDK_服务端_项目sdkAddProject】申请项目异常", e);
        }
    }

   /**
    * <desc>
    *      获取SDK项目的项目信息
    * <desc/>
    * @param    appid     应用接入凭证
    * @param    projectId     独立开发者所管辖的项目Id
    * @return   Message   老版标准格式化响应结果
    * @author Biao.R
    * @createDate 2017/11/6
    */
   @ResponseBody
   @RequestMapping("/app/getProjectInfo")
   public Message getProjectInfo(String appid, String projectId, Integer pageNo, Integer pageSize) {
       try {
           JSONArray projectArr = new JSONArray();
           //验证appid是该项目的独立开发者
           String desProjectId = DesEncryptUtil.projectIdDesEncrypt(projectId);
          /* if (desProjectId == null  ) {
               return new Message(Code.SDK_PROJECTID_ERR);
           }
           //校验开发者账号是否有该项目的权限
           Message message = checkServerSDKofProject(appid, desProjectId);
           if (message != null) {
               return message;
           }*/

           //查询该独立开发者的项目信息
           PropertyRoleProjectPO roleProjectPO = new PropertyRoleProjectPO(desProjectId, PropertyPublicRoleEnum.DEVELOPER.getRoleId(), appid);
           List<ProjectPO> projectPOS = iSDKProjectServiceClient.getDeveloperProjects(roleProjectPO);
           if (projectPOS != null && !projectPOS.isEmpty()) {
               for (ProjectPO projectPO : projectPOS) {
                   JSONObject js = new JSONObject();
                   js.put("projectId", DesEncryptUtil.projectIdEncrypt(projectPO.getProjectId(), null, null));
                   js.put("projectName", projectPO.getProjectName());
                   projectArr.add(js);
               }
           }
           JSONObject js = new JSONObject();
           js.put("projectInfoArr", projectArr);
           js.put("totalNumber", projectArr.size());
           return new Message(Code.SUCCESS, js);
       } catch (Exception e) {
           throw new DataAccessException("【SDK_服务端_项目getProjectInfo】获取SDK项目的项目信息异常", e);
       }
   }

    /**
     * <desc>
     *      校验开发者账号是否有该项目的权限
     * <desc/>
     * @param   appid     应用接入凭证
     * @param    projectId     独立开发者所管辖的项目Id
     * @return  Message   老版标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/11/6
     */
    private Message checkServerSDKofProject(String appid, String projectId) {
        PropertyRoleProjectPO roleProjectPO = new PropertyRoleProjectPO(projectId, PropertyPublicRoleEnum.DEVELOPER.getRoleId(), appid);
        List<PropertyRoleProjectPO> roleProjectPOS = iSDKUserServiceClient.getRoleProject(roleProjectPO);
        if (roleProjectPOS != null && roleProjectPOS.isEmpty()) {
            return new Message(Code.NOT_PERMISSION);
        }
        return null;
    }


    /**
     * <desc>
     *      SDK添加楼栋
     * <desc/>
     * @param       appid     应用接入凭证
     * @param    projectId     独立开发者所管辖的项目Id
     * @param    projectId     独立开发者所管辖的项目Id
     * @param    buildJson     待添加的楼栋信息Json
     * @return  Message   老版标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/11/6
     */
    @ResponseBody
    @RequestMapping("/app/build/add")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_ADD_BUILD_LOG_DESC)
    public Message sdkAddBuild(String appid, String projectId, String buildJson) {
        try {
            String desProjectId = DesEncryptUtil.projectIdDesEncrypt(projectId);
            if (desProjectId == null  ) {
                return new Message(Code.APP_DEVELOP_ERR);
            }
            //校验开发者账号是否有该项目的权限
            Message message = checkServerSDKofProject(appid, desProjectId);
            if (message != null) {
                return message;
            }
            JSONArray errarray = new JSONArray();
            List<PropertyProjectGetBuildInfoDTO> buildSdkAddDtoList = new ArrayList<>();
            int count = 0;
            Date currentTime = new Date();
            //解析buildJson
            try {
                JSONObject parseObject = JSONObject.parseObject(buildJson);
                buildSdkAddDtoList = JSONObject.parseObject(parseObject.getString("buildArr"), new TypeReference<List<PropertyProjectGetBuildInfoDTO>>() {
                });
            } catch (Exception e) {
                return new Message(Code.PARAM_ERR, String.format("%s%s", "解析buildJson异常:", buildJson));
            }
            if (buildSdkAddDtoList == null || buildSdkAddDtoList.isEmpty()) {
                return new Message(Code.NOT_PARAM, String.format("%s%s", "请检查buildArr格式或数量:", buildSdkAddDtoList));
            }
            for (PropertyProjectGetBuildInfoDTO buildDTO : buildSdkAddDtoList) {
                if (!buildDTO.getBuildNum().trim().matches("\\d{3}") || StringUtils.isEmpty(buildDTO.getBuildName())) {
                    errarray.add(JSONObject.toJSON(String.format("%s%s", " 楼栋名称不能为空或楼栋编号长度必须为3位 ", buildDTO.getBuildNum())));
                } else {
                    // 判断新添加的楼栋信息是否已经存在
                    //楼栋层数默认99
                    Integer floorNum = buildDTO.getFloorNum();

                    Map<String, Object> param = new HashMap<>();
                    param.put("projectId", desProjectId);
                    param.put("buildNum", buildDTO.getBuildNum());
                    List<BuildInfoPO> buildInfos = iSDKBuildServiceClient.getBuildByParam(param);
                    //添加或更新
                    if (buildInfos != null && !buildInfos.isEmpty()) {
                        BuildInfoPO buildPO = buildInfos.get(0);
                        if (!(buildDTO.getBuildNum()).equals(buildPO.getBuildName()) || floorNum!=buildPO.getFloorNum()) {
                            buildPO.setFloorNum(floorNum==null?99:floorNum);
                            buildPO.setUpdateTime(currentTime);
                            buildPO.setGroundFloorNum(buildPO.getFloorNum());
                            buildPO.setUndergroundFloorNum(0);
                            buildPO.setStatus(DataStatusEnum.NORMAL.getType());
                            count += iSDKBuildServiceClient.update(buildPO);
                        }
                    } else {
                        BuildInfoPO buildInfo = new BuildInfoPO(desProjectId, LogicIdUtil.bussinessId(), buildDTO.getBuildNum(), buildDTO.getBuildName(), floorNum);
                        buildInfo.setStatus(DataStatusEnum.NORMAL.getType());
                        buildInfo.setRemark("sdk添加");
                        buildInfo.setBuildType(1);
                        buildInfo.setGroundFloorNum(buildInfo.getFloorNum());
                        buildInfo.setFloorNum(floorNum==null?99:floorNum);
                        buildInfo.setUndergroundFloorNum(0);
                        buildInfo.setCreateTime(currentTime);
                        count += iSDKBuildServiceClient.save(buildInfo);
                    }
                }
            }
            String errStr = "";
            if (errarray.size() > 0) {
                errStr = ",未添加的异常数据：" + errarray.toJSONString();
            }
            if (count > 0) {
                return new Message(Code.SUCCESS, String.format("%s%s", "本次总共添加或更新了：" + count + " 条数据", errStr));
            }
            return new Message(Code.ERROR, "添加的数据已存在,或存在异常的数据" + errStr);
        } catch (Exception e) {
            return new Message(Code.PARAM_ERR);
        }
    }


   /**
    * <desc>
    *      添加单元
    * <desc/>
    * @param    appid     应用接入凭证
    * @param    projectId  待添加单元的小区ID
    * @param    unitJson  待添加的单元数据Json
    * @return   Message   老版标准格式化响应结果
    * @author Biao.R
    * @createDate 2017/11/9
    */
    @ResponseBody
    @RequestMapping("/app/unit/add")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_ADD_UNIT_LOG_DESC)
    public Message sdkAddUnit(String appid, String projectId, String unitJson) {
        try {
            System.out.println("添加单元：" + unitJson);
            String desProjectId = DesEncryptUtil.projectIdDesEncrypt(projectId);
            if (desProjectId == null  ) {
                return new Message(Code.APP_DEVELOP_ERR);
            }
            //校验开发者账号是否有该项目的权限
            Message message = checkServerSDKofProject(appid, desProjectId);
            if (message != null) {
                return message;
            }
            Date currentTime = new Date();
            JSONArray errarray = new JSONArray();
            List<SDKUnitInfoSaveDTO> unitSdkAddDtoList = null;
            try {
                if (StringUtils.isNotEmpty(unitJson)) {
                    JSONObject unitJ = JSONObject.parseObject(unitJson);
                    unitSdkAddDtoList = JSONObject.parseObject(unitJ.getString("unitArr"), new TypeReference<List<SDKUnitInfoSaveDTO>>() {
                    });
                } else {
                    return new Message(Code.NOT_PARAM, "unitJson不能为空" + unitJson);
                }
            } catch (Exception e) {
                return new Message(Code.PARAM_ERR, String.format("%s%s", "解析unitJson异常:", unitJson));
            }
            int count = 0;
            if (unitSdkAddDtoList != null && unitSdkAddDtoList.size() > 0) {
                try {
                    for (SDKUnitInfoSaveDTO unitSdkAddDto : unitSdkAddDtoList) {
                        if (!unitSdkAddDto.getUnitNum().trim().matches("\\d{2}") || StringUtils.isEmpty(unitSdkAddDto.getUnitName())) {
                            errarray.add(JSONObject.toJSON(" 单元名称不能为空或单元编号长度不等于2位 " + unitSdkAddDto.getUnitNum()));
                        }
                        //查询楼栋是否存在
                        Map<String, Object> param = new HashMap<>();
                        param.put("projectId", desProjectId);
                        param.put("buildNum", unitSdkAddDto.getBuildNum());
                        List<BuildInfoPO> buildInfos = iSDKBuildServiceClient.getBuildByParam(param);
                        if (null != buildInfos && !buildInfos.isEmpty()) {
                            //查询单元是否存在
                            BuildInfoPO buildInfo = buildInfos.get(0);
                            param.put("buildId", buildInfo.getBuildId());
                            param.put("unitNum", unitSdkAddDto.getUnitNum());
                            List<UnitInfoPO> unitPOs = iSDKServerOldUnitServiceClient.getUnitByParam(param);
                            if (unitPOs != null && !unitPOs.isEmpty()) {
                                UnitInfoPO unitInfoPO = unitPOs.get(0);
                                if (!(unitSdkAddDto.getUnitName()).equals(unitInfoPO.getUnitName())) {
                                    unitInfoPO.setUnitName(unitSdkAddDto.getUnitName());
                                    unitInfoPO.setUpdateTime(currentTime);
                                    Integer update = iSDKServerOldUnitServiceClient.update(unitInfoPO);
                                    count += update;
                                }
                            } else {
                                // 如果数据库中没有该数据，则添加
                                UnitInfoPO unitInfoPO = new UnitInfoPO(desProjectId, buildInfo.getBuildId(), LogicIdUtil.bussinessId(), unitSdkAddDto.getUnitNum(),
                                        unitSdkAddDto.getUnitName(), (String.format("%s%s", buildInfo.getBuildNum(), unitSdkAddDto.getUnitNum())).replaceAll("^(0+)", ""));
                                unitInfoPO.setCreateTime(currentTime);
                                unitInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                                Integer save = iSDKServerOldUnitServiceClient.save(unitInfoPO);
                                count += save;
                            }
                        }
                    }
                } catch (Exception e) {
                    errarray.add(JSONObject.toJSON(unitSdkAddDtoList));
                }
            } else {
                return new Message(Code.NOT_PARAM, "请检查unitArr格式或数量!" + unitSdkAddDtoList);
            }
            String errStr = "";
            if (errarray.size() > 0) {
                errStr = ",未添加的异常数据：" + errarray.toJSONString();
            }
            if (count > 0) {
                return new Message(Code.SUCCESS, "本次总共添加或更新了：" + count + " 条数据" + errStr);
            } else {
                return new Message(Code.ERROR, "添加的数据已存在,或存在异常的数据" + errStr);
            }
        } catch (Exception e) {
            throw new DataAccessException("【SDK_服务端_项目地址服务】添加单元异常", e);
        }
    }

    /**
     * <desc>
     *      获取SDK项目的楼栋与单元信息
     * <desc/>
     * @param    projectId  查询项目ID
     * @param    buildNum   查询楼栋编号
     * @param    unitNum   查询单元编号
     * @return      Message   老版标准格式化响应结果
     * @author  Biao.R
     * @createDate 2017/11/9
     */
    @ResponseBody
    @RequestMapping("/app/getBuildAndUnitInfo")
    public Message getBuildAndUnitInfo(String appid, String projectId, String buildNum, String unitNum) {
        try {
            String desProjectId = DesEncryptUtil.projectIdDesEncrypt(projectId);
            if (desProjectId == null  ) {
                return new Message(Code.APP_DEVELOP_ERR);
            }
            //校验开发者账号是否有该项目的权限
            Message message = checkServerSDKofProject(appid, desProjectId);
            if (message != null) {
                return message;
            }
            JSONObject js = new JSONObject();
            ProjectPO projectPO = iSDKProjectServiceClient.getByProjectId(desProjectId);
            if (projectPO == null) {
                return new Message(Code.APP_DEVELOP_ERR);
            }
            js.put("projectId", DesEncryptUtil.projectIdEncrypt(projectPO.getProjectId(), null, null));
            js.put("projectName", projectPO.getProjectName());

            JSONArray buildArr = new JSONArray();
            Map<String, Object> param = new HashMap<>();
            param.put("projectId", desProjectId);
            param.put("buildNumIn", buildNum);
            List<BuildInfoPO> buildPOs = iSDKBuildServiceClient.getBuildByParam(param);
            if (buildPOs != null && !buildPOs.isEmpty()) {
                for (BuildInfoPO buildPO : buildPOs) {
                    JSONObject buildjs = new JSONObject();
                    buildjs.put("buildNum", buildPO.getBuildNum());
                    buildjs.put("buildName", buildPO.getBuildName());
                    param.put("buildId", buildPO.getBuildId());
                    param.put("unitNumIn", unitNum);
                    List<UnitInfoPO> unitPOs = iSDKServerOldUnitServiceClient.getUnitByParam(param);
                    if (unitPOs != null && !unitPOs.isEmpty()) {
                        JSONArray unitArr = new JSONArray();
                        for (UnitInfoPO unitPO : unitPOs) {
                            JSONObject unitjs = new JSONObject();
                            unitjs.put("unitNum", unitPO.getUnitNum());
                            unitjs.put("unitName", unitPO.getUnitName());
                            unitArr.add(unitjs);
                        }
                        buildjs.put("unitInfoArr", unitArr);
                    }
                    buildArr.add(buildjs);
                }
            }
            js.put("buildInfoArr", buildArr);
            return new Message(Code.SUCCESS, js);
        } catch (Exception e) {
            throw new DataAccessException("【SDK_服务端_项目地址服务】获取楼栋单元信息异常", e);
        }
    }

    /**
     * <desc>
     *      SDK添加房间
     * <desc/>
     * @param       appid     应用接入凭证
     * @param    projectId  待添加房间的小区ID
     * @param    roomJson  待添加的房间数据Json
     * @return   Message   老版标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/11/9
     */
    @ResponseBody
    @RequestMapping("/app/room/add")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_ADD_ROOM_LOG_DESC)
    public Message sdkRoomUnit(String appid, String projectId, String roomJson)  {
        try {
            String desProjectId = DesEncryptUtil.projectIdDesEncrypt(projectId);
            if (desProjectId == null  ) {
                return new Message(Code.APP_DEVELOP_ERR);
            }
            //校验开发者账号是否有该项目的权限
            Message message = checkServerSDKofProject(appid, desProjectId);
            if (message != null) {
                return message;
            }
            Date currentTime = new Date();
            List<SDKRoomInfoSaveDTO> roomSaveDTOList = new ArrayList<>();
            try {
                if (StringUtils.isNotEmpty(roomJson)) {
                    JSONObject jsonObject = JSONObject.parseObject(roomJson);
                    roomSaveDTOList = JSONObject.parseObject(jsonObject.getString("roomArr"), new TypeReference<List<SDKRoomInfoSaveDTO>>() {
                    });
                } else {
                    return new Message(Code.NOT_PARAM, "roomJson不能为空" + roomJson);
                }
            } catch (Exception e) {
                return new Message(Code.PARAM_ERR, String.format("%s%s", "解析unitJson异常:", roomJson));
            }
            JSONArray errarray = new JSONArray();
            int count = 0;
            if (null != roomSaveDTOList && roomSaveDTOList.size() > 0) {
                for (SDKRoomInfoSaveDTO roomSaveDTO : roomSaveDTOList) {
                    try {
                        String roomNum = roomSaveDTO.getRoomNum();
                        if (StringUtils.isEmpty(roomSaveDTO.getRoomName()) || !roomNum.trim().matches("\\d{4}")) {
                            errarray.add(" 房间名称不能为空或房间编号长度不等于4位:" + roomNum);
                            continue;
                        }
                        Map<String, Object> param = new HashMap<>();
                        param.put("projectId", desProjectId);
                        param.put("buildNum", roomSaveDTO.getBuildNum());
                        param.put("unitNum", roomSaveDTO.getUnitNum());
                        List<UnitInfoPO> unitPOs = iSDKServerOldUnitServiceClient.getUnitByParam(param);
                        if (unitPOs != null && !unitPOs.isEmpty()) {
                            UnitInfoPO unitInfoPO = unitPOs.get(0);
                            param.put("unitId", unitInfoPO.getUnitId());
                            param.put("roomNum", roomNum);
                            List<RoomInfoPO> roomPOs = iSDKRoomServiceClient.getRoomByParam(param);
                            if (roomPOs != null && !roomPOs.isEmpty()) {
                                RoomInfoPO roomPO = roomPOs.get(0);
                                roomPO.setRoomName(roomSaveDTO.getRoomName());
                                roomPO.setUpdateTime(currentTime);
                                Integer update = iSDKRoomServiceClient.update(roomPO);
                                count += update;
                            } else {
                                // 如果数据库中没有该房间数据，则添加
                                RoomInfoPO roomInfoPO = new RoomInfoPO(desProjectId, unitInfoPO.getBuildId(), unitInfoPO.getUnitId(), LogicIdUtil.bussinessId(),
                                        roomNum, roomSaveDTO.getRoomName(), roomNum.replaceAll("^(0+)", ""), 1);
                                roomInfoPO.setRoomType(1);
                                roomInfoPO.setRoomStatus(5);
                                roomInfoPO.setCreateTime(currentTime);
                                roomInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                                Integer save = iSDKRoomServiceClient.save(roomInfoPO);
                                count += save;
                            }
                        }
                    } catch (Exception e) {
                        errarray.add(JSONObject.toJSON(roomSaveDTO));
                    }
                }
            } else {
                return new Message(Code.NOT_PARAM, "请检查 roomArr 格式或数量!" + roomSaveDTOList);
            }
            String errStr = "";
            if (errarray.size() > 0) {
                errStr = ",未添加的异常数据：" + errarray.toJSONString();
            }
            if (count > 0) {
                return new Message(Code.SUCCESS, "本次共添加或更新了：" + count + "条数据" + errStr);
            } else {
                return new Message(Code.ERROR, "添加的数据已存在,或存在异常的数据" + errStr);
            }
        } catch (Exception e) {
            throw new DataAccessException("【SDK_服务端_项目地址服务】添加房间异常", e);
        }
    }

}